<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客首页</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://cdn.ckeditor.com/ckeditor5/35.3.2/classic/ckeditor.js"></script>
    <link rel="stylesheet" href="/static/index.css">
</head>
<body>
<div class="action-bar">
    <button class="action-btn" id="profileButton">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
            <circle cx="12" cy="7" r="4"></circle>
        </svg>
        个人中心
    </button>
    <button class="action-btn" id="addpostButton">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2zM8 7h.01M12 7h.01M16 7h.01"></path>
        </svg>
        发表博文
    </button>
    <button class="action-btn" id="collectButton">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path>
        </svg>
        我的收藏
    </button>
</div>

<h1>首页</h1>

<form id="searchForm" class="search-container">
    <input type="text" id="searchKeyword" placeholder="输入关键字进行搜索...">
    <button type="button" onclick="searchProducts()">搜索</button>
</form>
<!--<div class="category-buttons">-->
<!--    <button onclick="location.href='/type/post?id=1'">动漫</button>-->
<!--    <button onclick="location.href='/type/post?id=2'">游戏</button>-->
<!--    &lt;!&ndash;<button onclick="location.href='/user/userinfo?id=1'">进入个人主页</button>&ndash;&gt;-->
<!--    <button onclick="location.href='/type/post?id=3'">漫画</button>-->
<!--</div>-->
<h2>分类</h2>
<div id="button-container" class="category-buttons"></div>
<script>
    // id到文本映射
    const buttonTexts = {
        1: '小白必看',
        2: '前沿突破',
        3: '实际应用',
        4: '行业新闻',
        5: '技术文章',
        6: '电商方向',
        7: '工业方向',
        8: '金融方向',
        9: '医疗方向',
        10: '生活随笔'
    };

    // 获取用于放置按钮的容器
    const container = document.getElementById('button-container');

    // 遍历映射并创建按钮
    Object.keys(buttonTexts).forEach(id => {
        const button = document.createElement('button');
        button.textContent = buttonTexts[id]; // 设置按钮文本
        button.onclick = () => {
            location.href = `/type/postHTML?id=${id}`; // 设置点击事件，跳转URL
        };
        container.appendChild(button); // 将按钮添加到容器中
    });
</script>
<h2>博文</h2>
<div class="posts-grid" id="postGrid"></div>
<script>
    //个人中心按钮逻辑
    $(document).ready(function() {
        $('#profileButton').click(function() {
            const token = localStorage.getItem('token'); // 从 localStorage 中获取 token
            if (!token) {
                if (confirm("未登录，请先登录！是否跳转到登录页面？")) {
                    window.location.href = '/login'; // 跳转到登录页面
                }
                return;
            }
            console.log("从本地拿到的token是",token)//
            // 使用带有 token 的请求跳转到个人信息页
            fetch('/userinfo', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Token': token
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        // 跳转到个人信息页
                        window.location.href = '/userinfoHTML';
                    } else {
                        Swal.fire({
                            icon: 'info',
                            title: '信息提示',
                            text: '未查询到用户信息，请您填写',
                            confirmButtonText: '前往填写'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                showUserInfoForm();
                            }
                        });
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showUserInfoForm();
                });
        });
    });
    //发表博文按钮逻辑
    let editor;
    $('#addpostButton').click(function() {
        const token = localStorage.getItem('token');
        if (!token) {
            if (confirm("未登录，请先登录！是否跳转到登录页面？")) {
                window.location.href = '/login';
            }
            return;
        }
        Swal.fire({
            title: '发表博文',
            // 修改后的表单HTML结构
            html: `
<div class="vertical-form">
    <div class="form-item floating-label">
        <input type="text" id="postTitle" required placeholder=" ">
        <label>文章标题</label>
    </div>

    <div class="form-item">
        <label>文章简介</label>
        <textarea id="postBrief" placeholder="用简洁的文字吸引读者..."></textarea>
    </div>

    <div class="form-item">
        <label>正文内容</label>
        <div id="postContent"></div>
    </div>

    <div class="form-item floating-label">
        <input type="url" id="postImageUrl" placeholder=" ">
        <label>封面图URL（可选）</label>
    </div>
</div>
            `,
            focusConfirm: false,
            showCancelButton: true,
            confirmButtonText: '提交',
            preConfirm: () => {
                return {
                    title: document.getElementById('postTitle').value.trim(),
                    brief: document.getElementById('postBrief').value.trim(),
                    // 使用 CKEditor 的 getData 方法获取内容
                    content: editor ? editor.getData() : '',
                    imageurl: document.getElementById('postImageUrl').value.trim()
                };
            },
            inputValidator: (values) => {
                if (!values.title) return '标题不能为空！';
                return null;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = result.value;
                const params = new URLSearchParams();
                params.append('title', formData.title);
                params.append('brief', formData.brief);
                params.append('content', formData.content);
                params.append('imageurl', formData.imageurl);

                fetch('/api/v1/post', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Token': token
                    },
                    body: params
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 0) {
                            Swal.fire('成功', '博文发表成功', 'success').then(() => {
                                window.location.reload();
                            });
                        } else {
                            Swal.fire('错误', data.msg || '发表失败', 'error');
                        }
                    })
                    .catch(error => {
                        Swal.fire('网络错误', '请检查连接后重试', 'error');
                    });
            }
        });

        // 初始化 CKEditor
        ClassicEditor.create( document.querySelector( '#postContent' ) )
            .then( newEditor => {
                editor = newEditor;
                console.log( editor );
            } )
            .catch( error => {
                console.error( error );
            } );
    });
    //我的收藏
    $(document).ready(function() {
        $('#collectButton').click(function() {
            const token = localStorage.getItem('token'); // 从 localStorage 中获取 token
            if (!token) {
                if (confirm("未登录，请先登录！是否跳转到登录页面？")) {
                    window.location.href = '/login'; // 跳转到登录页面
                }
                return;
            }
            console.log("从本地拿到的token是",token)
            // fetch('/user/postcollect', {
            //     method: 'GET',
            //     headers: {
            //         'Content-Type': 'application/json',
            //         'Token': token
            //     }
            // })
            //     .then(response => response.json())
            //     .then(data => {
            //         if (data.code === 0) {
            //             // 跳转到收藏夹页
            window.location.href = '/user/postcollectHTML';
            //     }
            // })
            // .catch(error => {
            //     console.error('Error:', error);
            // });
            //
        });
    });

    //用户信息填写
    function showUserInfoForm() {
        const uid = localStorage.getItem('uid');

        Swal.fire({
            title: '完善个人信息',
            html: `
        <div class="vertical-form">
            <div class="form-item">
                <label>用户名</label>
                <input type="text" id="username" required placeholder="请输入2-20位字符">
            </div>

            <div class="form-item">
                <label>手机号</label>
                <input type="tel" id="phonenumber" pattern="\\d{11}" placeholder="请输入11位手机号码">
            </div>

            <div class="form-item">
                <label>性别</label>
                <div class="radio-group">
                    <label><input type="radio" name="sex" value="男" checked> 男</label>
                    <label><input type="radio" name="sex" value="女"> 女</label>
                    <label><input type="radio" name="sex" value="隐藏"> 隐藏</label>
                </div>
            </div>

            <div class="form-item">
                <label>地址</label>
                <input type="text" id="address" placeholder="请输入省市区信息">
            </div>

            <div class="form-item">
                <label>邮箱</label>
                <input type="email" id="email" placeholder="请输入邮箱">
            </div>
        </div>
        `,

            focusConfirm: false,
            showCancelButton: false,
            confirmButtonText: '提交信息',
            width: 500,  // 适当增加弹窗宽度
            customClass: {
                popup: 'vertical-form-popup',
                htmlContainer: 'vertical-form-container'
            },
            didOpen: () => {
                // 动态调整输入框宽度
                console.log('弹窗已打开！'); // 查看控制台是否输出
                document.querySelectorAll('.swal2-input').forEach(input => {
                    input.style.width = '300px';
                });
            },
            preConfirm: () => {
                return {
                    uid: uid,
                    username: document.getElementById('username').value.trim(),
                    phonenumber: document.getElementById('phonenumber').value.trim(),
                    sex: document.querySelector('input[name="sex"]:checked').value,
                    address: document.getElementById('address').value.trim(),
                    email: document.getElementById('email').value
                }
            },
            inputValidator: (values) => {
                if (!values.username) return '用户名不能为空！';
                if (values.phonenumber && !/^\d{11}$/.test(values.phonenumber)) {
                    return '手机号格式不正确';
                }
                return null;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                submitUserInfo(result.value);
            }
        });
    }
    //表单提交逻辑
    function submitUserInfo(formData) {
        const token = localStorage.getItem('token');

        // 创建表单数据对象
        const params = new URLSearchParams();
        params.append('username', formData.username);
        params.append('phonenumber', formData.phonenumber);
        params.append('sex', formData.sex);
        params.append('address', formData.address);
        params.append('email', formData.email);

        fetch('/userinfo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Token': token
            },
            body: params
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    Swal.fire('成功', '信息保存成功', 'success').then(() => {
                        window.location.reload();
                    });
                } else {
                    Swal.fire('错误', data.msg || '保存失败', 'error');
                }
            })
            .catch(error => {
                Swal.fire('网络错误', '请检查连接后重试', 'error');
            });
    }
    //关键词搜索
    function fetchPosts(searchKeyword = '') {
        let url = '/api/v1/post';
        if (searchKeyword) {
            url += `/searchkw?kw=${encodeURIComponent(searchKeyword)}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                const postGrid = document.getElementById('postGrid');
                postGrid.innerHTML = '';

                data.data.forEach(post => {
                    const card = document.createElement('article');
                    card.className = 'post-card';
                    card.innerHTML = `
          <img src="${post.imageurl}" alt="${post.title}" class="post-image">
          <div class="post-content">
            <h3 class="post-title">${post.title}</h3>
            <p class="post-brief">${post.brief}</p>
            <button class="btn btn-primary"
                    onclick="location.href='/api/v1/post/searchpidHTML?id=${post.pid}'">
              阅读全文 →
            </button>
          </div>
        `;
                    postGrid.appendChild(card);
                });
            })
            .catch(error => console.error('Error:', error));
    }

    function searchProducts() {
        const searchKeyword = document.getElementById('searchKeyword').value;
        fetchPosts(searchKeyword);
    }

    window.onload = function() {
        fetchPosts(); // 在页面加载时获取所有博文
    };
</script>
</body>
</html>